package logic

import (
	"context"
	"fmt"
	"user/models/mysql"
	"user/pkg"

	"user/internal/svc"
	"user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameLogic) RealName(in *user.RealNameRequest) (*user.RealNameResponse, error) {
	// todo: add your logic here and delete this line

	r := mysql.RealName{}
	err := r.CheckoutRealName(int(in.UserId), in.IdCard)
	if err != nil {
		logx.Error("数据库查询失败")
		return nil, fmt.Errorf("数据库查询失败")

	}

	if r.ID != 0 {
		logx.Error("实名认证成功")
		return nil, fmt.Errorf("实名认证成功")
	}

	if !pkg.TenXunYun(in.IdCard, in.Name) {
		logx.Error("第三方实名认证失败")
		return nil, fmt.Errorf("第三方实名认证失败")
	}

	r.UserId = int(in.UserId)
	r.IdCard = in.IdCard
	r.Name = in.Name

	err = r.Create()

	if err != nil {
		logx.Error("用户信息创建成功")
		return nil, fmt.Errorf("用户信息创建成功")
	}

	return &user.RealNameResponse{Id: in.UserId}, nil
}
